﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DistributedLock
{
    public class Mutex
    {
        static Mutex()
        {
            NodeEventMapping = new Dictionary<string, AutoResetEvent>();
        }

        static object _lock = new object();

        static Dictionary<string, AutoResetEvent> NodeEventMapping { get; set; }

        public static void Wait(string node)
        {
            AutoResetEvent @event = null;
            lock (_lock)
            {
                if (!NodeEventMapping.ContainsKey(node))
                {
                    @event = new AutoResetEvent(false);
                    NodeEventMapping.Add(node, @event);
                }
                else
                {
                    @event = NodeEventMapping[node];
                }
            }

            @event.WaitOne();
        }

        public static void Continue(string node)
        {
            if (NodeEventMapping.ContainsKey(node))
            {
                var @event = NodeEventMapping[node];
                @event.Set();
                NodeEventMapping.Remove(node);
            }
        }
    }
}
